package com.csun.dsms.controller;

import com.csun.dsms.comment.core.annotation.Authorization;
import com.csun.dsms.comment.core.annotation.CurrentUser;
import com.csun.dsms.comment.core.utils.wrapper.WrapMapper;
import com.csun.dsms.comment.core.utils.wrapper.Wrapper;
import com.csun.dsms.model.domain.DsmsFee;
import com.csun.dsms.model.domain.DsmsUser;
import com.csun.dsms.model.vo.FeeVo;
import com.csun.dsms.model.vo.ServiceRecordVo;
import com.csun.dsms.service.DsmsFeeService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/fee")
public class DsmsFeeController {

    @Resource
    private DsmsFeeService dsmsFeeServiceImpl;

    /*
    *结算管理查看
    * */
    @RequestMapping(value = "/query", method = RequestMethod.POST)
    public Wrapper feeQuery(@RequestBody FeeVo feeVo){
        List<FeeVo> feeVos  = dsmsFeeServiceImpl.feeQuery(feeVo);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE,new PageInfo<>(feeVos));
    }

    /*
     *结算管理详情查看
     * */
    @RequestMapping(value = "/queryByArea",method = RequestMethod.POST)
    public Wrapper feeQueryByArea(@RequestBody FeeVo feeVo){
        List<ServiceRecordVo> serviceRecordVos = dsmsFeeServiceImpl.feeQueryByArea(feeVo);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE,serviceRecordVos);
    }

    /*
     *结算管理结算
     * */
    @Authorization
    @RequestMapping(value = "/settlement",method = RequestMethod.POST)
    public Wrapper feeSettlement(@CurrentUser DsmsUser login, @RequestBody DsmsFee feeVo) throws ParseException {
        feeVo.setStatus(1);
        feeVo.setUpdateTime(new Date());
        feeVo.setLastOperatorId(login.getId());
        feeVo.setLastOperator(login.getLoginName());
        FeeVo fee = new FeeVo();
        fee.setId(feeVo.getId());
        List<FeeVo> feeVos = dsmsFeeServiceImpl.feeQuery(fee);
        Date createdTime = feeVos.get(0).getCreatedTime();
        Date nowTime = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String format = sdf.format(nowTime);
        DateFormat df = new SimpleDateFormat("yyyy-MM");
        if(createdTime.before(df.parse(format))) {
            Integer i = dsmsFeeServiceImpl.update(feeVo);
            if (i < 1) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, Wrapper.ERROR_MESSAGE);
            }
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE);
        }
        return WrapMapper.wrap(Wrapper.ERROR_CODE,"请在下月进行结算");
    }
}
